﻿using MediatR;
using RBAC_Class.Write.API.Application.Command.Permissions;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;

namespace RBAC_Class.API.Application.CommandHandler.Permissions
{
    public class DeletePermissionCommandHandler:IRequestHandler<DeletePermissionCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly ILogger<DeletePermissionCommandHandler> logger;

        public DeletePermissionCommandHandler(IBaseRepository<Permission> permissionRep, ILogger<DeletePermissionCommandHandler> logger)
        {
            this.permissionRep = permissionRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = permissionRep.GetAll().FirstOrDefault(x => x.PermissionID == request.PermissionID);
                list.IsDelete = true;
                permissionRep.Update(list);
                return Task.FromResult(new APIResult<int>
                {
                    Code = ResultCode.Success,
                    Message = "删除成功",
                    Data = 1
                });
            }
            catch (Exception ex)
            {
                logger.LogError("删除出错", ex);
                throw;
            }
            
        }
    }
}
